package com.yang.framework;

import com.yang.po.Response;
import com.yang.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Description: 请求处理器
 * @author: Yang Qiang
 * @create: 2021-11-13 15:58
 */
@Slf4j
@Component
public class RequestDispatcher {

    @Autowired
    private YangBeanPostProcessors yangBeanPostProcessors;

    /**
     * 处理请求
     * @param commandStr: commandStr+methodStr确定到具体哪一个方法
     * @param methodStr
     * @param param: 参数信息
     * @param clientIp: ip地址
     * @return
     */
    public Response dispatcher(String commandStr, String methodStr, String param, String clientIp) {
        // 1 声明一个开始时间
        long startTime = System.currentTimeMillis();
        Map requestMap = null;

        try {
            // 2 把ip地址添加到参数里面去
            param = JsonUtil.putString(param, "clientIp", clientIp);

            // 3 把参数转换为map
            Map map = JsonUtil.toMap(param);

            // 4 得到方法
            ApiMethodInfo apiMethod = yangBeanPostProcessors.getApiMethod(commandStr, methodStr);
            if (apiMethod == null){
                return Response.ParamError();
            }

            // 5 调用方法
            Object execute = apiMethod.execute(param);

            return Response.SUCCESS().putAll((Map) execute);
        }catch (Exception e){
            log.error(e.getMessage());
        }finally {
            //保存请求记录，如果参数解析失败
            if(requestMap != null){
                requestStatistics(startTime,requestMap);
            }
        }
        return Response.ParamError();
    }


    //记录log日志
    private void requestStatistics(long startTime, Map param) {
        Long endTime = System.currentTimeMillis();
        String command = (String)param.get("command");
        String method = (String)param.get("method");
        String channel = (String)param.get("channel");
        String userId = (String)param.get("userId");
        String phone = (String)param.get("phone");
        String requestId= MDC.get("requestId");
        String interfaceCode = command + method;
        // 这里可以将数据录入数据，方便后面的分析可以放到es, mongo里面，我们这里打印一下日志信息
        log.info("调用接口入库channel：{}, userId:{}, phone:{}, requestId:{},interfaceCode:{}" +
                "startTime:{},endTime:{}",channel,userId,phone,requestId,interfaceCode,startTime,endTime);
    }
}
